﻿namespace Chain.Tasks
{
    using System;
    using System.Collections.Generic;
    using System.Xml;

    public class TaskManager
    {
        private static readonly TaskManager _taskManager = new TaskManager();
        private readonly List<TaskThread> _taskThreads = new List<TaskThread>();

        public void Initialize(XmlNode node)
        {
            this._taskThreads.Clear();
            foreach (XmlNode node2 in node.ChildNodes)
            {
                if (node2.Name.ToLower() == "thread")
                {
                    TaskThread item = new TaskThread(node2);
                    this._taskThreads.Add(item);
                    foreach (XmlNode node3 in node2.ChildNodes)
                    {
                        if (node3.Name.ToLower() == "task")
                        {
                            XmlAttribute attribute = node3.Attributes["type"];
                            Type taskType = Type.GetType(attribute.Value);
                            if (taskType != null)
                            {
                                Task task = new Task(taskType, node3);
                                item.AddTask(task);
                            }
                        }
                    }
                    continue;
                }
            }
        }

        public void Start()
        {
            foreach (TaskThread thread in this._taskThreads)
            {
                thread.InitTimer();
            }
        }

        public void Stop()
        {
            foreach (TaskThread thread in this._taskThreads)
            {
                thread.Dispose();
            }
        }

        public static TaskManager Instance
        {
            get
            {
                return _taskManager;
            }
        }
    }
}

